import os
import numpy as np
import time
from multiprocessing import Pool
import argparse
from PIL import Image


parser = argparse.ArgumentParser(description="Process .image files to jpeg pairs.")
parser.add_argument("inputfolder", help="Input folder name.")
parser.add_argument("outputfolder", help="Output folder name.")
parser.add_argument("-Imagename", help="Imagename.", default="image#")
parser.add_argument("-partheader", help="Where to start transfering .image to .jpeg", type=int, default=0)
parser.add_argument("-parttailer", help="Where to stop transfering .image to .jpeg", type=int, default=260)
parser.add_argument("-pixle_x", help="pixle_x", type=int, default=2048)
parser.add_argument("-pixle_y", help="pixle_y", type=int, default=1548)

args = parser.parse_args()

Imagename = args.Imagename
output = args.outputfolder
inpath = args.inputfolder
startI = args.partheader
endI = args.parttailer
pixle_x=args.pixle_x
pixle_y=args.pixle_y

def Image2Jpeg(pathin,pathout):
    #以二进制格式读取文件
    f = open(file=pathin,mode='rb')
    data = f.read()
    #空过文件前a行
    a=3181
    
    #创建两个数组分别存储两帧图像数据
    Im_1=np.zeros((pixle_y,pixle_x)) 
    Im_2=np.zeros((pixle_y,pixle_x)) 
    for j in range(pixle_y):
        for i in range(pixle_x):
            index1 = a+i*pixle_y*2+j*2
            Im_1[pixle_y-j-1][i]=int(str(bin(data[index1+1]))+str(bin(data[index1])[2:].zfill(8)),2)
    for j in range(pixle_y):
        for i in range(pixle_x):
            index2 = a+pixle_x*pixle_y*2+i*pixle_y*2+j*2
            Im_2[pixle_y-j-1][i]=int(str(bin(data[index2+1]))+str(bin(data[index2])[2:].zfill(8)),2)
    
    #将矩阵按照图片格式写出
    image = Image.fromarray(Im_1)
    if image.mode == "F":
        image = image.convert('RGB') 
    image.save(pathout+'_1.jpeg')
    
    image = Image.fromarray(Im_2)
    if image.mode == "F":
        image = image.convert('RGB') 
    image.save(pathout+'_2.jpeg')
    f.close()
    return 0

def transfer(i):

    isExists=os.path.exists(output)
    if not isExists:
        os.mkdir(output)
        
    suffix=Imagename
    pathin=os.path.join(inpath,suffix+str(i)+'.image')
    pathout=os.path.join(output,suffix+str("%06d" % i))
    Image2Jpeg(pathin,pathout)

def batchTransfer():
    result = [0 for t in range(startI,endI)]
    for i in range(startI,endI):
        result[i]=i
    cores = os.cpu_count()

    pool = Pool(cores)
    try:
        pool.map(transfer, result[startI:endI])
    finally:
        pool.close()

if __name__=="__main__":
    
    start = time.time()
    batchTransfer()

    print('Elapsed Time: ', time.time() - start)
